<template>
  <el-dialog
    title="分享落地页配置"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <el-form-item label="购买页图片">
        <!-- <el-input v-model="form.name" auto-complete="off"></el-input> -->
        <!--:http-request="handleRequest"-->
        <el-upload
          :limit="15"
          class="upload-demo"
          ref="upload"
          list-type="picture"
          multiple
          :action="url"
          :on-success="handleUploadImageOK"
          :on-remove="handleRemove"
          :before-upload="checkSame"
          :file-list="fileList"
          :on-change="handleChange"
          :on-exceed="overNum"
          accept="image/jpg,image/jpeg,image/png"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
          <div slot="tip" class="el-upload__tip">请上传1125宽度的图片，小于250KB，最多上传15张图片，待文件上传完成后可拖动顺序</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">返回</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<style>

</style>
<script>
  import $ from 'jquery'
  export default {
    data() {
      return {
        visible: false,
        url: '',
        dialogVisible: false,
        dialogImageUrls: '',
        fileList: [],
        dataForm: {
          sharePageImgList: [],
        }
      }
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/operate/shareInfo/upload?token=${this.$cookie.get('token')}`
      )
    },
    updated() {
      const liList = document.querySelectorAll('.el-upload-list__item');
      const that = this;
      window.dragElement = null;
      liList.forEach((item, index) => {
        item.setAttribute('draggable', true);
        item.ondragstart = (e) => {
          // 记录的拖动节点
          window.dragElement = item;
          e.dataTransfer.setData('text/html', item.innerHTML);
          e.dataTransfer.setData('textIndex', index);
        };
        item.ondragover = (e) => {
          // 不执行无法进入drop事件
          e.preventDefault();
        };
        item.ondrop = () => {
          if (window.dragElement !== item) {
            const nIndex = +$(item).index();
            // 被插入的节点交换元素值
            const dragIndex = +$(window.dragElement).index();
            const dragFormItem = that.dataForm.sharePageImgList[dragIndex];
            const fileListItem = that.fileList[dragIndex];
            // 移除数组的
            that.dataForm.sharePageImgList.splice(dragIndex, 1);
            that.fileList.splice(dragIndex, 1);
            that.dataForm.sharePageImgList.splice(nIndex, 0, dragFormItem);
            that.fileList.splice(nIndex, 0, fileListItem);
          }
          // const a = that.groupForm.qrCodeImages.map(qrItem => qrItem.imageName);
          // console.log('TCL: item.ondrop -> a', a);
          // console.log('flistlist', this.fileList);
        };
      });
    },
    methods: {
      init() {
        this.visible = true
        this.fileList = []
        this.$http({
          url: this.$http.adornUrl(
            `/operate/shareInfo/querySharePageImg`
          ),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm.sharePageImgList = data.sharePageImgList
            data.sharePageImgList.map((item) => {
              this.fileList.push({id: item.id, url: item.imgUrl})
            })
          }
        })
      },
      overNum() {
        this.$message.error('最多上传15张图片!')
      },
      handleUploadImageOK(res, file, fileList) {
        const that = this;
        fileList.map((item, index) => {
          if (item.name === file.name) {
            that.dataForm.sharePageImgList[index] = {
              id: index,
              imgUrl: res.url
            }
          }
          return true;
        });
        this.fileList = fileList;
      },
      // 移除图片id
      handleRemove(file, fileList) {
        console.log(file)
        const newImageList =
          this.dataForm.sharePageImgList.filter(item => (item.imgUrl !== file.url));
        this.dataForm.sharePageImgList = newImageList;
        // const a = this.groupForm.qrCodeImages.map(qrItem => qrItem.imageName);
        // console.log('remove -> a', a);
        this.fileList = fileList;
      },
      checkSame(file) {
        const that = this;
        for (let i = 0; i < that.fileList.length; i += 1) {
          if (that.fileList[i].name === file.name) {
            that.$message.error('禁止上传相同的图片');
            return false
          }
        }
        const is250K = file.size / 1024 < 250
        if (!is250K) {
          this.$message.error('上传的图片要小于250KB!')
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 1125
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function() {
            let valid = img.width == width
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file)
        }).then(
          () => {
            return file
          },
          () => {
            this.$message.error('上传的图片宽度必须是1125!')
            return reject()
          }
        )
        return is250K && isSize
      },
      handleChange(file, fileList) {
        this.loading = true;
        if (fileList.length > 0) this.localFileList = fileList;
        console.log('​handleChange -> his.localFileList', this.localFileList.length);
      },
      // 表单提交
      dataFormSubmit() {
        this.dataForm.sharePageImgList.map((item, index) => {
          item.id = index
        })
        console.log(this.dataForm)
        this.$http({
          url: this.$http.adornUrl(
            `/operate/shareInfo/saveSharePageImg`
          ),
          method: 'post',
          data: this.dataForm.sharePageImgList
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        })
      }
    }
  }
</script>
